package com.af.system.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author : zhenyun.su
 * @comment : String 工具
 * @since : 2022/5/19
 * history:
 *   20220901: 新增字符串拼接函数 , stringBuilder()，stringBuilderD(), stringBuilderDPS(), stringBuffer(), stringJoiner(),stringJoinerAll()
 */

public abstract class AfStringUtils {
    public static final String UTF_8 = "UTF-8";
    public static final String TIME_ZONE = "Asia/Shanghai";
    public static final String LOCALE = "zh-CN";

    public static final String PERCENT = "%";
    public static final String COMMA = ",";
    public static final String WINDOW_SLASH = "/";
    public static final String LINUX_SLASH = "'\'";
    public static String[] RMB_UPPER_CASE = new String[]{"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};

    public final static String TRUE = "true";
    public final static String FALSE = "false";
    public final static String SUCCESS = "success";
    public final static String FAILURE = "failure";
    public final static String YES = "yes";
    public final static String NO = "no";

    public static boolean isEmpty(String str){
        return str == null || str.length() == 0;
    }

    public static String getValue(Object str, String defaultValue){
        if (str == null){
            return defaultValue;
        }
        if (str.toString().length() == 0){
            return defaultValue;
        }
        return str.toString();
    }

    public static String getValue(Object str){
        return getValue(str, null);
    }

    public static boolean hasText(String str) {
        return str != null && str.length() >= 1 && containsText(str);
    }

    private static boolean containsText(CharSequence str) {
        int strLen = str.length();

        for(int i = 0; i < strLen; ++i) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return true;
            }
        }
        return false;
    }

    public static void emptyError(String value, String hint) throws Exception {
        if (value == null || value.length() <= 0){
            throw new Exception(hint);
        }
    }

    /**
     * @comment : 若空则返回""; 不空则返回去掉前后空格的字符串
     */
    public static String emptyString(String str) {
        return str == null ? "" : str.trim();
    }

    /**
     * @comment : 按UTF-8编码，截取length长度字符串
     * 例如：  subStringByUTF8("中国33人", 4)，返回中国
     */
    public static String subStringByUTF8(String value, Integer length) {
        try {
            if ((value == null) && (value == "")) {
                return null;
            }
            byte[] sourceBytes = value.getBytes(UTF_8);
            if (sourceBytes.length <= length) {
                return value;
            } else {
                byte[] targetBytes = new byte[length];
                System.arraycopy(sourceBytes, 0, targetBytes, 0, length - 1);
                return new String(targetBytes);
            }
        } catch (Exception E) {
            // nothing
            return null;
        }
    }

    /**
     * @comment : 返回 %str%字符串，可用于spring-data-jpa like查询
     */
    public static String percent(String str) {
        str = str == null? "":str.trim();
        return PERCENT + str + PERCENT;
    }

    /**
     * @comment : 生成count位随机整数
     */
    public static int randomInt(int count) {
        return (int) ((Math.random() * 9 + 1) * 10 * count);
    }

    public static String randomInt(int min, int max) {
        int ran = (int) (Math.random() * (max - min) + 1);
        return String.valueOf(ran);
    }
    public static String Replace(String value) {
        String regEx = "[`~!@#$%^&*()\\-+={}':;,\\[\\].<>/?￥%…（）_+|【】‘；：”“’。，、？\\s]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(value);
        return m.replaceAll("");
    }
    /**
     * @comment : 根据字符串和分隔符，返回String的List对象
     * 例如：  asStringList("dog@cat@bear", "@")
     */
    public static List<String> asStringList(String values, String regex) {
        if (values == null) {
            return null;
        }
        if (regex == null) {
            regex = COMMA;
        }
        return Arrays.asList(values.split(regex));
    }

    /**
     * @comment : 根据字符串和分隔符，返回Integer的List对象
     * 例如：  asIntegerList("1,2,3", ",")
     */
    public static List<Integer> asIntegerList(String values, String regex) {
        if (values == null) {
            return null;
        }
        if (regex == null) {
            regex = COMMA;
        }
        String[] arrayString = values.split(regex);
        List<Integer> lists = new ArrayList<>();
        for (String item : arrayString) {
            lists.add(Integer.valueOf(item.trim()));
        }
        return lists;
    }

    public static List<Long> asLongList(String values, String regex) {
        if (values == null) {
            return null;
        }
        if (regex == null) {
            regex = COMMA;
        }
        String[] arrayString = values.split(regex);
        List<Long> lists = new ArrayList<>();
        for (String item : arrayString) {
            lists.add(Long.valueOf(item.trim()));
        }
        return lists;
    }

    public static String urlEncode(String value) {
        try{
            return java.net.URLEncoder.encode(value, UTF_8);
        }catch(Exception e){
            return value;
        }
    }

    /*
     * @comment : 单线程字符串拼接, delimiter, prefix, suffix
     */
    public static String stringBuilder(String ...args){
        if (args == null || args.length == 0){
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (String arg : args) {
            sb.append(arg);
        }
        return sb.toString();
    }
    /*
     * @comment : 单线程字符串拼接, D=delimiter
     */
    public static String stringBuilderD(CharSequence delimiter, String ...args){
        if (args == null || args.length == 0){
            return "";
        }
        StringBuilder sb = new StringBuilder(args[0]);
        for (int i = 1; i < args.length ; i++) {
            sb.append(delimiter).append(args[i]);
        }
        return sb.toString();
    }
    /*
     * @comment : 单线程字符串拼接, D=delimiter, P=prefix, S=suffix
     */
    public static String stringBuilderDPS(CharSequence delimiter,
                                          CharSequence prefix,
                                          CharSequence suffix,
                                          String ...args){
        if (args == null || args.length == 0){
            return "";
        }
        StringBuilder sb = new StringBuilder(prefix).append(args[0]).append(suffix);
        for (int i = 1; i < args.length ; i++) {
            sb.append(delimiter).append(prefix).append(args[i]).append(suffix);
        }
        return sb.toString();
    }

    /*
     * @comment : 单线程字符串拼接
     */
    public static String stringBuffer(String ...args){
        if (args == null || args.length == 0){
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (String arg : args) {
            sb.append(arg);
        }
        return sb.toString();
    }

    /*
     * @comment : 单线程字符串拼接
     */
    public static String stringJoiner(CharSequence delimiter, String ...args){
        if (args == null || args.length == 0){
            return "";
        }
        StringJoiner sj = new StringJoiner(delimiter);
        for (String arg : args) {
            sj.add(arg);
        }
        return sj.toString();
    }

    /*
     * @comment : 单线程字符串拼接
     */
    public static String stringJoinerAll(CharSequence delimiter,
                                      CharSequence prefix,
                                      CharSequence suffix,
                                      String ...args){
        if (args == null || args.length == 0){
            return "";
        }
        StringJoiner sj = new StringJoiner(delimiter, prefix, suffix);
        for (String arg : args) {
            sj.add(arg);
        }
        return sj.toString();
    }

    // 按字符串右边填充空格到固定长度
    private String fillChar(String character, int targetWidth) {
        if (isEmpty(character)){
            return repeat("", targetWidth);
        }
        if (character.length() <= targetWidth){
            return character;
        }
        return character + repeat(" ", targetWidth - character.length());
    }

    // 重复拼接字符串
    private String repeat(String space, int count) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < count; i++) {
            sb.append(space);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(stringBuilder("George","Sally","Fred"));
        System.out.println(stringBuilderD(",", "George","Sally","Fred"));
        System.out.println(stringBuilderDPS(",", "\"", "\"", "George","Sally","Fred"));
        System.out.println(stringJoiner(":","hello","word","name"));
        System.out.println(stringJoinerAll(":", "[", "]", "hello","word","name"));
    }
}


